package com.irononetech.ots.webservice.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class AttachmentDownloadService extends IntentService {

	public static final String EXTRA_MEDIA_URL = "extra_media_url";
	public static final String EXTRA_MEDIA_SAVE_PATH = "extra_media_save_path";
	public static final String EXTRA_MEDIA_SAVE_NAME = "extra_media_save_name";
	
	private File mediaFile;

	public AttachmentDownloadService() {
		super("AttachmentDownloadService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String mediaUrl = intent.getStringExtra(EXTRA_MEDIA_URL);
		String mediaSavePath = intent.getStringExtra(EXTRA_MEDIA_SAVE_PATH);
		String mediaSaveName = intent.getStringExtra(EXTRA_MEDIA_SAVE_NAME);
		Log.v("AttachmentDownloadService", "downloading: "+ mediaSaveName);
		try {
			URL url = new URL(mediaUrl);
			File filet = new File(mediaSavePath);
			if(!filet.exists())
				filet.mkdirs();

			mediaFile = new File(filet+File.separator+mediaSaveName);
			File tempFile = new File(filet+File.separator+mediaSaveName + "_temp");
			URLConnection ucon = url.openConnection();
			InputStream is = ucon.getInputStream();
			FileOutputStream os = new FileOutputStream(tempFile);
			
			BufferedInputStream bis = new BufferedInputStream(is);
    		BufferedOutputStream bos = new BufferedOutputStream(os);
    		byte[] buf = new byte[1024];

    		int n = 0;
    		int o = 0;
    		while ((n = bis.read(buf, o, buf.length)) != -1) {
    			bos.write(buf, 0, n);
    		}

    		bis.close();
    		bos.close();
    		
			tempFile.renameTo(mediaFile);
		} catch (IOException e) {
			if(mediaFile.exists()){
				mediaFile.delete();
			}
		}

	}
}
